package com.yyx.up.web.controller;

import com.yyx.up.web.bean.Admin;
import com.yyx.up.web.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Description: 管理员的控制器对象
 * @Author: yyx
 * @Create: 2023/5/26 20:06
 * @Version: 8
 */
@Controller
public class AdminController {
    @Autowired
    private AdminService adminService;

    // 向用户登录页面跳转
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String toLogin() {
        return "login";
    }

    // 向用户注册页面跳转
    @RequestMapping(value = "/toRegister")
    public String toRegister() {
        return "register";
    }

    @RequestMapping(value = "/addAdmin")
    public String addAdmin(Admin admin, Model model) {
        // 从数据库获取值
        List<Admin> list = adminService.findAllAdmins();
        for (Admin admin0 : list) {
            if (admin.getName().equals(admin0.getName())) {
                model.addAttribute("msg", "该用户名已注册！");
                return "register";
            }
        }
        adminService.addAdmin(admin);
        model.addAttribute("msg", "您已注册成功！点击右下角去登录！");
        return "register";
    }

    // 用户登录
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Admin admin, Model model, HttpSession Session) {
        // 获取用户名和密码
        String name = admin.getName();
        String password = admin.getPassword();
        // 从数据库获取值
        List<Admin> list = adminService.findAllAdmins();
        for (Admin admin0 : list) {
            if (name != null && name.equals(admin0.getName()) && password != null
                    && password.equals(admin0.getPassword())) {
                // 将用户对象添加到Session
                Session.setAttribute("ADMIN_SESSION", admin);
                // 重定向到主页面的跳转方法
                return "queryFilmDatas";
            }
            if ( name.equals(admin0.getName()) && !password.equals(admin0.getPassword())) {
                model.addAttribute("msg", "密码错误，请重新输入！");
                return "login";
            }
        }
        model.addAttribute("msg", "该用户未注册，请点击右下角注册！");
        return "login";
    }

    // 退出登录
    @RequestMapping(value = "/logout")
    public String logout(HttpSession Session) {
        // 清除Session
        Session.invalidate();
        return "redirect:login";
    }
}
